package com.vcredit.creditcat.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.framework.util.HttpClientUtil;
import com.vcredit.creditcat.vo.BUIGridResultVo;
import com.vcredit.creditcat.vo.IncomeInfoVo;
import com.vcredit.creditcat.vo.IncomeSearchParamVo;
import com.vcredit.framework.util.JacksonUtil;

@Controller
@RequestMapping("business/income")
public class IncomeController {
	
	@Value("${business.income.listUrl}")
	private String incomeListUrl;
	
	@Value("${business.income.addUrl}")
	private String incomeAddUrl;
	
	@Value("${business.income.incomeTypeListUrl}")
	private String incomeTypeListUrl;
	
	@RequestMapping("page")
	public String toPage() {
		return "business/income";
	}
	
	@RequestMapping("pageQuery")
	@ResponseBody
	public BUIGridResultVo<IncomeInfoVo> pageQuery(@Valid IncomeSearchParamVo param){
		try {
			String json = HttpClientUtil.doPostByJson(incomeListUrl, param);
			Map<String, Object> result = JacksonUtil.Json2Map(json);
			if("000".equals((String)result.get("status"))){
				return JacksonUtil.Json2Obj(JacksonUtil.Obj2Json(result.get("data")),
						new TypeReference<BUIGridResultVo<IncomeInfoVo>>() {});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping("add")
	@ResponseBody
	public String add(@Valid @RequestBody IncomeInfoVo income) {
		try {
			String json = HttpClientUtil.doPostByJson(incomeAddUrl, income);
			Map<String, Object> result = JacksonUtil.Json2Map(json);
			if("000".equals((String)result.get("status")) && (Boolean)result.get("data"))
					return "success";
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "fail";
	}
	
	@RequestMapping("incomeTypeList")
	@ResponseBody
	public Map<Integer,String>  incomeTypeList() {
		Map<Integer,String> result = new HashMap<Integer,String>();
		try {
			String json = HttpClientUtil.doPostByJson(incomeTypeListUrl, "{}");
			Map<String, Object> resultMap = JacksonUtil.Json2Map(json);
			if("000".equals((String)resultMap.get("status"))) {
				List<Map<String,Object>> list = (List<Map<String,Object>>)resultMap.get("data");
				for (Map<String, Object> map : list) {
					result.put((Integer)map.get("incomeTypeId"), (String)map.get("incomeFromName"));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}
